package com.quanxiaoha.weblog.web.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.quanxiaoha.weblog.web.config.AiConfig;
import com.quanxiaoha.weblog.web.model.dto.ai.OpenAiChatRequestDTO;
import com.quanxiaoha.weblog.web.model.dto.ai.OpenAiChatResponseDTO;
import com.quanxiaoha.weblog.web.service.AiConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.util.Collections;

/**
 * @author: 犬小哈
 * @url: www.quanxiaoha.com
 * @date: 2024-01-15
 * @description: AI API调用工具类
 **/
@Component
@Slf4j
public class AiApiUtil {

    @Autowired
    private AiConfigService aiConfigService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 调用AI聊天API
     * @param request 请求对象
     * @return AI响应
     */
    public OpenAiChatResponseDTO chatCompletion(OpenAiChatRequestDTO request) {
        AiConfig aiConfig = aiConfigService.getCurrentAiConfig();
        if (!aiConfig.isEnabled()) {
            log.warn("AI功能已禁用");
            return null;
        }

        try {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setBearerAuth(aiConfig.getApiKey());
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

            // 设置请求体
            String requestBody = objectMapper.writeValueAsString(request);
            HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

            log.info("发送AI请求: {}", requestBody);

            // 发送请求
            String url = aiConfig.getApiUrl() + "/chat/completions";
            ResponseEntity<String> response = restTemplate.exchange(
                    url, 
                    HttpMethod.POST, 
                    entity, 
                    String.class
            );

            log.info("AI响应状态: {}", response.getStatusCode());
            log.info("AI响应内容: {}", response.getBody());

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                return objectMapper.readValue(response.getBody(), OpenAiChatResponseDTO.class);
            } else {
                log.error("AI API调用失败，状态码: {}", response.getStatusCode());
                return null;
            }

        } catch (Exception e) {
            log.error("调用AI API发生异常", e);
            return null;
        }
    }

    /**
     * 构建聊天请求
     * @param userMessage 用户消息
     * @param systemPrompt 系统提示
     * @return 请求对象
     */
    public OpenAiChatRequestDTO buildChatRequest(String userMessage, String systemPrompt) {
        AiConfig aiConfig = aiConfigService.getCurrentAiConfig();
        return OpenAiChatRequestDTO.builder()
                .model(aiConfig.getModel())
                .temperature(0.7)
                // 移除maxTokens限制，让AI自由生成回复长度
                .stream(false)
                .messages(java.util.Arrays.asList(
                        OpenAiChatRequestDTO.Message.builder()
                                .role("system")
                                .content(systemPrompt)
                                .build(),
                        OpenAiChatRequestDTO.Message.builder()
                                .role("user")
                                .content(userMessage)
                                .build()
                ))
                .build();
    }

    /**
     * 从响应中提取回复内容
     * @param response AI响应
     * @return 回复内容
     */
    public String extractReplyContent(OpenAiChatResponseDTO response) {
        if (response == null || response.getChoices() == null || response.getChoices().isEmpty()) {
            return null;
        }

        OpenAiChatResponseDTO.Choice choice = response.getChoices().get(0);
        if (choice.getMessage() == null) {
            return null;
        }

        return choice.getMessage().getContent();
    }

    /**
     * 使用AI扩展用户查询关键词
     * @param userQuery 用户查询
     * @return 扩展后的关键词列表
     */
    public String enhanceQueryWithAi(String userQuery) {
        AiConfig aiConfig = aiConfigService.getCurrentAiConfig();
        if (!aiConfig.isEnabled()) {
            return userQuery;
        }

        try {
            String systemPrompt = "你是一个专业的技术关键词扩展助手。请根据用户的查询，生成相关的技术关键词，用于文章推荐。\n\n" +
                    "要求：\n" +
                    "1. 分析用户查询的技术领域和意图\n" +
                    "2. 生成5-10个相关的技术关键词\n" +
                    "3. 包括同义词、相关技术、常见术语\n" +
                    "4. 只返回关键词，用逗号分隔，不要其他解释\n" +
                    "5. 关键词应该是中文和英文混合\n\n" +
                    "示例：\n" +
                    "用户查询：数据库\n" +
                    "输出：数据库,database,MySQL,SQL,Redis,MongoDB,数据存储,CRUD,索引,事务";

            OpenAiChatRequestDTO request = buildChatRequest(userQuery, systemPrompt);
            OpenAiChatResponseDTO response = chatCompletion(request);
            String enhancedKeywords = extractReplyContent(response);

            if (enhancedKeywords != null && !enhancedKeywords.trim().isEmpty()) {
                log.info("AI增强关键词 - 原查询: [{}], 增强后: [{}]", userQuery, enhancedKeywords);
                return userQuery + "," + enhancedKeywords;
            }
        } catch (Exception e) {
            log.warn("AI关键词增强失败: {}", e.getMessage());
        }

        return userQuery;
    }
} 